<?php

namespace Apps\Manage\Controllers;


use Apps\Common\Libs\Keyword;
use Apps\Common\Libs\UploadPic;
use Apps\Common\Models\OmQuestionAnswerUser;
use Apps\Common\Models\Question;
use Apps\Common\Models\QuestionAnswer;
use Apps\Common\Models\QuestionTag;
use PhalconPlus\Common\ResponseResult;
use PhalconPlus\Common\ResponseResultStatus;

/**
 * 问题回答管理
 * @author     chenxiaolin
 * @date        2016年1月19日
 * @version     2.0.0
 * @copyright   Copyright 2016 meelier.com
 */
class QaaddController extends BaseController
{
    public function initialize()
    {
        parent::initialize();
        $this->setMainNav('qaadd');
    }

    public function indexAction()
    {
        $this->response->redirect('qaadd/list');
    }

    /**
     * 问题列表
     */
    public function listAction()
    {
        $this->setLeftNav('list');
        $req = $this->request;
        $page = intval($req->getQuery('page', null, 1));
        $page = $page > 0 ? $page : 1;
        $limit = $this->pageNavLimit;
        $offset = $limit * ($page - 1);

        $filterTag = intval($req->getQuery('filterTag', null, -10000));
        $filterOrder = intval($req->getQuery('filterOrder', null, 0));

        $columns = [
            'Apps\Common\Models\Question.question_id',
            'ub.user_id',
            'ub.user_nickname',
            'ub.user_cover',
            'Apps\Common\Models\Question.question_tag',
            'Apps\Common\Models\Question.question_content',
            'Apps\Common\Models\Question.question_pics',
            'Apps\Common\Models\Question.answer_num',
            'Apps\Common\Models\Question.question_follows',
            'Apps\Common\Models\Question.question_browsers',
            'Apps\Common\Models\Question.question_state',
            'Apps\Common\Models\Question.question_addtime',
            'Apps\Common\Models\Question.city_code'
        ];
        $where = [];
        $bind = [];
        if($filterTag > 0) {
            $where[] = 'Apps\Common\Models\Question.question_tag = :tag:';
            $bind['tag'] = $filterTag;
        }
        // 只查询正常的内容
        $where[] = 'Apps\Common\Models\Question.question_state > 0';

        $whereStr = implode(' AND ', $where);
        $query = Question::query()
            ->columns($columns)
            ->leftJoin('Apps\Common\Models\UserBase', 'ub.user_id = Apps\Common\Models\Question.user_id', 'ub');
        if(count($where) > 0) {
            $query = $query->where($whereStr)->bind($bind);
        }
        $data = $query
            ->orderBy($filterOrder == 1 ? 'answer_num ASC, Apps\Common\Models\Question.question_id DESC' : 'Apps\Common\Models\Question.question_id DESC')
            ->limit($limit, $offset)
            ->execute();
        //总数
        $total = Question::count([
            'conditions' => $whereStr,
            'bind' => $bind,
        ]);

        $this->view->setVar('data', $data);
        $this->view->setVar('page', $page);
        $this->view->setVar('limit', $limit);
        $this->view->setVar('total', $total);

       // $this->view->setVar('tagList', QuestionTag::query()->columns('*')->orderBy('tag_order DESC, tag_id ASC')->execute());

        $this->view->setVar('filterTag', $filterTag);
        $this->view->setVar('filterOrder', $filterOrder);
    }

    /**
     * 回答问题
     */
    public function answerAction()
    {
        $req = $this->request;
        if(!$req->isPost()) {
            $id = intval($req->getQuery('id', null, 0));
            // 查询他匹配的用户
            $data = OmQuestionAnswerUser::query()
                ->columns([
                    'qau_id',
                    'ub.user_id',
                    'ub.user_account',
                    'ub.user_nickname',
                ])
                ->leftJoin('Apps\Common\Models\UserBase', 'ub.user_id = Apps\Common\Models\OmQuestionAnswerUser.user_id', 'ub')
                ->where('op_id = :opId:', ['opId' => $this->operator->id])
                ->execute();
            $this->view->setVar('userList', $data);
            $this->view->setVar('id', $id);
            return;
        }

        $response = new ResponseResult();
        $response->callback = $req->getPost('callback', null, 'parent.setFormResult');
        $response->callbackJavascriptTag = true;

        $id = intval($req->getPost('question_id', null, 0));
        if($id <= 0) {
            $response->sendError(ResponseResultStatus::PARAM_CANNOT_EMPTY, '参数问题！');
            return $response;
        }
        $content = Keyword::Filter($req->getPost('answer_content', null, ''));
        $userId = intval($req->getPost('answer_user', null, 0));

        // 判断空数据
        if(empty($content) || $userId < 1) {
            $response->sendError(ResponseResultStatus::PARAM_CANNOT_EMPTY, '参数异常！');
            return $response;
        }

        $up = new UploadPic();
        $questionPics = json_encode($up->questionPic());
        // 查询最大楼层
        $floor = QuestionAnswer::maximum([
            "column" => "answer_floor",
            "conditions" => "question_id = :qid:",
            "bind" => [
                "qid" => $id
            ]
        ]);
        $qa = new QuestionAnswer();
        $qa->user_id = $userId;
        $qa->question_id = $id;
        $qa->answer_content = $content;
        $qa->answer_floor = ($floor ? $floor : 0) + 1;
        $qa->answer_pics = $questionPics;
        if($qa->save()){
            // 记录回答数
            Question::updateAnswerNum($id);
            $response->sendResult($qa->answer_id);
        } else {
            $this->databaseErrorLog($qa);
            $response->sendError(ResponseResultStatus::DATABASE_ERROR, '保存数据异常！');
        }
        return $response;
    }
}